<template>
  <div>
    <a-row :gutter="8">
      <a-spin :spinning="spinning">
        <a-card :bordered="true" title="用户基础信息">
          <a href="#" slot="extra" @click="cacenlEdit">返回</a>
          <a-form :form="editForm">
            <a-row class="form-row">
              <a-col :span="10" :offset="1">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="姓名"
                >
                  <a-input v-decorator="['name',{rules: [{ required: true, message: '请输入姓名' },{ max:10,message:'长度不能超过10个字'}]}]"/>
                </a-form-item>
              </a-col>
              <a-col :span="10" :offset="1">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="账号"
                >
                  <a-input :disabled="editType === '2'?true:false" v-decorator="['accout',{rules: [{ required: true, message: '请输入账号' },{ max:10,message:'长度不能超过10个字'}]}]"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="form-row">
              <a-col :span="10" :offset="1">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="性别"
                >
                  <a-select placeholder="请选择" v-decorator="['sex',{rules: [{ required: false, message: '请选择性别' }]}]">
                    <a-select-option value="男">男</a-select-option>
                    <a-select-option value="女">女</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>
        <a-card :bordered="true" title="组织信息">
          <a-row>
            <a-col :span="10" :offset="1">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="所属组织"
              >
                <a-tree-select
                  :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                  :treeData="treeOfOrg"
                  treeDefaultExpandAll
                  allowClear
                  @change="orgChange"
                  style="width:100%"
                  :value="orgid"
                ></a-tree-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card :bordered="true" title="角色信息">
          <a-row>
            <a-col :span="10" :offset="1">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="选择角色"
              >
                <a-select
                  placeholder="请选择"
                  mode="multiple"
                  v-model="rolechecked"
                  @change="roleChange"
                  style="width:100%"
                >
                  <a-select-option v-for="item in roleopts" :key="item.key">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row type="flex" justify="end">
            <a-col>
              <a-button type="primary" @click="saveUserInfo">保存</a-button>
            </a-col>
          </a-row>
        </a-card>
      </a-spin>
    </a-row>
  </div>
</template>
<script>
import { setTimeout } from 'timers'
import router from '../../router'
import { adduser, updateuser, getOrgTree, getuserInfo, getRoleList } from '@/api/admin'
export default {
  name: 'UserEdit',
  data () {
    return {
      // 响应式布局
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16, offset: 1 }
      },
      // 编辑页面信息传递
      userinfo: {},
      // 用户对应角色
      rolechecked: [],
      dataSource: [],
      // 绑定树选择的值
      orgid: '',
      orgname: '',
      spinning: false,
      indeterminate: false,
      checkAll: false,
      editForm: this.$form.createForm(this),
      treeOfOrg: [],
      editType: this.$route.query.editType,
      // 角色可选择集合
      roleopts: []
    }
  },
  created () {
    // 获取树形组织信息
    getOrgTree({ 'parentTreeId': 'root' }).then(res => {
      this.treeOfOrg = this.genernateTree(res.result.data)
    })
    this.showUserInfo(this.$route.query.item)
  },
  methods: {
    /**
     * 处理后台返回值 替换名字 id=>key label=>title
     * 处理与树型绑定值冲突问题
     */
    genernateTree (value) {
      value.forEach(item => {
        item.value = item.id + 'select'
        item.title = item.label
        item.key = item.id
        if (item.children && item.children.length) {
          this.genernateTree(item.children)
        }
      })
      return value
    },
    /**
     * 保存修改内容
     */
    saveUserInfo () {
      this.editForm.validateFields((err, values) => {
        // 除了用户基础信息必填项限制，在这里加，且需要有对应的提醒信息
        values.deptCode = this.orgid === undefined ? '' : this.orgid.replace('select', '')
        if (!err) {
          this.spinning = true
          if (this.editType === '1') {
            values.password = '123456'
            this.addUser(values)
          } else {
            this.updateUser(values)
          }
        }
      })
    },
    /**
     * 新增用户
     */
    addUser (values) {
      values.roleId = this.rolechecked
      return adduser(
        values
      ).then(
        res => {
          if (res.status === 200) {
            this.$notification['success']({
              message: '操作成功',
              duration: 2
            })
          } else {
            this.$notification['error']({
              message: res.message,
              duration: 4
            })
          }
        }
      ).catch((err) => {
        if (err || err.response || err.response) {
          this.$notification['error']({
            message: err.response.data.message,
            duration: 4
          })
        }
      }).finally(() => {
        this.spinning = false
        router.go(-1)
      })
    },
    updateUser (values) {
      values.id = this.userinfo.id
      values.roleId = this.rolechecked
      return updateuser(
        values
      ).then(
        res => {
          if (res.status === 200) {
            this.$notification['success']({
              message: '操作成功',
              duration: 2
            })
          } else {
            this.$notification['error']({
              message: res.message,
              duration: 4
            })
          }
        }
      ).catch((err) => {
        if (err || err.response || err.response) {
          this.$notification['error']({
            message: err.response.data.message,
            duration: 4
          })
        }
      }).finally(() => {
        this.spinning = false
        router.go(-1)
      })
    },
    /**
     * 返回
     */
    cacenlEdit () {
      router.go(-1)
      this.$notification['info']({
        message: '取消操作',
        duration: 2
      })
    },
    /**
     * 打开编辑用户信息弹出框
     */
    showUserInfo (item) {
      this.userinfo = Object.assign({}, item)
      setTimeout(() => {
        this.editForm.setFieldsValue({
          name: this.userinfo.name,
          sex: this.userinfo.sex,
          accout: this.userinfo.accout
        })
      }, 0)
      if (item !== '') {
        // 拷贝选中信息内容到userinfo
        this.orgid = item.deptCode === undefined ? '' : item.deptCode + 'select'
        getuserInfo(item.id).then(res => {
          // this.rolechecked = res.result.adminRoleEntity === undefined ? '' : res.result.adminRoleEntity.id
          // this.rolechecked = res.result.adminRoleEntity === undefined ? '' : res.result.adminRoleEntity.id.split(',')
          res.result.adminRoleEntity.forEach((itemrole, index) => {
            this.rolechecked.push(itemrole === undefined ? '' : itemrole.id)
          })
        })
      }
      // 加载所有角色 信息
      getRoleList().then(res => {
        const result = res.result.data
        result.forEach((res) => {
          this.roleopts.push({ 'key': res.id, 'title': res.name })
        })
      })
    },
    roleChange (value) {
      this.roles = value
    },
    handleUserInfo (roles) {
      this.rolechecked = roles.id
    },
    /**
     * 组织change事件
     */
    orgChange (value, name) {
      this.orgid = value
      this.orgname = name
    }
  }
}
</script>
<style scoped>
.form-row {
  margin-bottom: 10px
}
</style>
